package com.horse.three60;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.horse.utils.Constants;
import com.horse.utils.DownloadCompletionListener;
import com.horse.utils.DownloadingItem;
import com.horse.utils.ImageName;
import com.horse.utils.NoRepeatRandom;
import com.horse.utils.Utils;
import com.inapp.util.Base64;
import com.inapp.util.BillingService;
import com.inapp.util.CPurchaseObserver;
import com.inapp.util.Consts;
//import com.openfeint.api.OpenFeint;
//import com.openfeint.api.resource.Score;
//import com.openfeint.api.ui.Dashboard;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class HomeScreenActivity extends Activity implements OnClickListener {

	private int displayWidth;
	private int displayHeight;
	private Bitmap imageBitmap;

	private ImageView imageView;

	private Random random = new Random();
	private NoRepeatRandom nrr;
	private int imageIndex = -1;

	private int imagesToShow[] = { R.drawable.horse_00_2x,
			R.drawable.horse_01_2x, R.drawable.horse_02_2x,
			R.drawable.horse_03_2x, R.drawable.horse_04_2x,
			R.drawable.horse_05_2x };

	private boolean isExit;

	private ImageView learnView;
	private ImageView recallView;
	private ImageView vettalkView;
	private JSONObject jo;
	private String fileNames[];

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_home_screen);

		try {
			sharedPreferences = PreferenceManager
					.getDefaultSharedPreferences(this);
			sharedPreferences.registerOnSharedPreferenceChangeListener(ospcl);
			mHandler = new Handler();

			BillingService.register(new CPurchaseObserver(this, mHandler));
			mBillingService = new BillingService();
			mBillingService.setContext(this);
			mBillingService.restoreInAppTransactions();
		} catch (Exception e) {
			e.printStackTrace();
		}

		imageView = (ImageView) findViewById(R.id.imageView);

		learnView = (ImageView) findViewById(R.id.learnView);
		learnView.setOnClickListener(this);

		recallView = (ImageView) findViewById(R.id.recallView);
		recallView.setOnClickListener(this);

		vettalkView = (ImageView) findViewById(R.id.vettalkView);
		vettalkView.setOnClickListener(this);

		displayWidth = getWindowManager().getDefaultDisplay().getWidth();
		displayHeight = getWindowManager().getDefaultDisplay().getHeight();

		displayWidth = Math.max(displayWidth, displayHeight);
		displayHeight = Math.min(displayWidth, displayHeight);

		float factor = Utils.getWidthDpiFactor(this);
		Log.i("DREG", "Factor = " + factor);

		Log.i("DREG", "Ceil = " + (int) Math.ceil(9.4));
		Log.i("DREG", "Floor = " + (int) Math.floor(9.4));

		showImageInPeriod();

	}

	@Override
	protected void onDestroy() {
		try {
			if (sharedPreferences != null && ospcl != null) {
				sharedPreferences
						.unregisterOnSharedPreferenceChangeListener(ospcl);
			}
			mBillingService.unbind();
			BillingService.unregister();

		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			isExit = true;
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showImageInPeriod() {
		try {
			new AsyncTask<String, String, String>() {
				private boolean isInvisible;

				@Override
				protected void onPreExecute() {
					try {

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... arg0) {

					imageView.setBackgroundResource(imagesToShow[imageIndex]);

				}

				@Override
				protected String doInBackground(String... arg0) {
					try {
						while (!isExit) {
							if (imageIndex < (imagesToShow.length - 1)) {
								imageIndex++;
							} else {
								imageIndex = 0;
							}
							publishProgress("");
							Thread.sleep(4000);
						}

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.learnView:
			isExit = true;
			Intent intent = new Intent(HomeScreenActivity.this,
					LearningBeforeActivity.class);
			intent.putExtra(Constants.KEY_QUIZ, Constants.QUIZ_LEARNING);
			startActivity(intent);
			break;
		case R.id.recallView:
			isExit = true;
			Intent in = new Intent(HomeScreenActivity.this,
					RecallBeforeActivity.class);
			in.putExtra(Constants.KEY_QUIZ, Constants.QUIZ_RECALL);
			startActivity(in);
			break;

		case R.id.vettalkView:
			showVettalkScreen();
			break;
		
		default:
			break;
		}

	}

	private void showVettalkScreen() {
		try {
			boolean mainBundlePurchased = BillingService.isPurchased(
					sharedPreferences, Constants.BUNDLE_ITEM_ID);
			boolean musclesPurchased = BillingService.isPurchased(
					sharedPreferences, Constants.MUSCLE_ITEM_ID);
			boolean hoovesPurchased = BillingService.isPurchased(
					sharedPreferences, Constants.HOOF_ITEM_ID);
			boolean tendonsPurchased = BillingService.isPurchased(
					sharedPreferences, Constants.DEEP_ITEM_ID);
			boolean headPurchased = BillingService.isPurchased(
					sharedPreferences, Constants.HEAD_ITEM_ID);
			boolean organsPurchased = BillingService.isPurchased(
					sharedPreferences, Constants.ORGAN_ITEM_ID);

			List<DownloadingItem> downloadingItems = new ArrayList<DownloadingItem>();
			if (mainBundlePurchased || musclesPurchased) {
				if (!Utils.containsAllFiles(Constants.MUSLES_DIRECTORY,
						Arrays.asList(ImageName.MUSCLES_IMAGES))) {
					DownloadingItem di = new DownloadingItem();
					di.setACHIEVEMENT_ID(Constants.MUSCLE_THERAPIST_ACHIEVEMENT_ID);
					di.setBASE_URL(Constants.MUSCLES_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.MUSLES_DIRECTORY);
					di.setImageFileName(ImageName.MUSCLES_IMAGES);
					downloadingItems.add(di);
				}
			}
			if (mainBundlePurchased || hoovesPurchased) {
				if (!Utils.containsAllFiles(Constants.HOOFS_DIRECTORY,
						Arrays.asList(ImageName.HOOFS_IMAGES))) {
					DownloadingItem di = new DownloadingItem();
					di.setACHIEVEMENT_ID(Constants.HORSE_DENTIST_ACHIEVEMENT_ID);
					di.setBASE_URL(Constants.HOOVES_RETINAL_URL);
					di.setIMAGE_DIRECTORY(Constants.HOOFS_DIRECTORY);
					di.setImageFileName(ImageName.HOOFS_IMAGES);
					downloadingItems.add(di);
				}
			}
			if (mainBundlePurchased || tendonsPurchased) {
				if (!Utils.containsAllFiles(Constants.DEEP_MUSCLES_DIRECTORY,
						Arrays.asList(ImageName.TENDON_IMAGES))) {
					DownloadingItem di = new DownloadingItem();
					di.setACHIEVEMENT_ID(Constants.PRO_RIDER_WORLD_CHAMPION_ACHIEVEMENT_ID);
					di.setBASE_URL(Constants.TENDONS_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.DEEP_MUSCLES_DIRECTORY);
					di.setImageFileName(ImageName.TENDON_IMAGES);
					downloadingItems.add(di);
				}
			}
			if (mainBundlePurchased || headPurchased) {
				if (!Utils.containsAllFiles(Constants.HEAD_DIRECTORY,
						Arrays.asList(ImageName.HEAD_IMAGES))) {
					DownloadingItem di = new DownloadingItem();
					di.setACHIEVEMENT_ID(Constants.CHIROPRACTOR_ACHIEVEMENT_ID);
					di.setBASE_URL(Constants.HEAD_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.HEAD_DIRECTORY);
					di.setImageFileName(ImageName.HEAD_IMAGES);
					downloadingItems.add(di);
				}
			}
			if (mainBundlePurchased || organsPurchased) {
				if (!Utils.containsAllFiles(Constants.ORGANS_DIRECTORY,
						Arrays.asList(ImageName.ORGANS_IMAGES))) {
					DownloadingItem di = new DownloadingItem();
					di.setACHIEVEMENT_ID(Constants.FARRIER_ACHIEVEMENT_ID);
					di.setBASE_URL(Constants.ORGANS_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.ORGANS_DIRECTORY);
					di.setImageFileName(ImageName.ORGANS_IMAGES);
					downloadingItems.add(di);
				}
			}
			if (downloadingItems.size() > 0) {
				if (Utils.isDeviceOnline(HomeScreenActivity.this)) {
					Utils.downloadFiles(HomeScreenActivity.this,
							downloadingItems, new DownloadCompletionListener() {

								@Override
								public void onDownloadError(Exception exception) {
									Utils.showAlertMessage(
											HomeScreenActivity.this, null,
											exception.getMessage());
								}

								@Override
								public void onCompleteDownloading() {
									startVettalk();
								}
							});
				} else {
					Utils.showAlertMessage(HomeScreenActivity.this, null,
							"Please go online to download image files");
				}
			} else {
				startVettalk();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startVettalk() {
		try {
			isExit = true;
			Intent i = new Intent(HomeScreenActivity.this,
					VelTalkActivity.class);
			startActivity(i);
		} catch (Exception e) {
			e.fillInStackTrace();
		}
	}

	// ////////////////////////////INAPP_PURCHASE_RELATED//////////////////////////////////////

	private static final String KEY_PURCHASE_COMMAND = "COMMAND_PURCHASE";
	private static final String KEY_TIME = "t";
	private static final String KEY_ITEM_ID = "i";
	private Handler mHandler;

	private BillingService mBillingService;

	private SharedPreferences sharedPreferences;
	private final OnSharedPreferenceChangeListener ospcl = new OnSharedPreferenceChangeListener() {

		public void onSharedPreferenceChanged(final SharedPreferences sp,
				String key) {
			try {
				if (KEY_PURCHASE_COMMAND.equals(key)) {
					runOnUiThread(new Runnable() {
						public void run() {
							try {
								String object = sp.getString(
										KEY_PURCHASE_COMMAND, null);
								if (object != null) {
									JSONObject jo = new JSONObject(object);
									String itemId = jo.getString(KEY_ITEM_ID);
									//
									// Log.i("DREG", "ITEM_ID="+itemId);
									// sharedPreferences.edit()
									// .putBoolean(Base64.encode(itemId.getBytes()),
									// true)
									// .commit();
									// sharedPreferences
									// .edit()
									// .putLong(BillingService.KEY_IN_APP_PURCHASED_ITEM_CHANGED_TIME,
									// System.currentTimeMillis()).commit();
									//
									// Toast.makeText(HomeScreenActivity.this,
									// "PURCHASE="+BillingService.isPurchased(sharedPreferences,
									// itemId)
									// , Toast.LENGTH_LONG).show();
									//
									if (mBillingService.requestPurchase(itemId,
											Consts.ITEM_TYPE_INAPP, null)) {

										Toast.makeText(HomeScreenActivity.this,
												"Requesting to Google play",
												Toast.LENGTH_LONG).show();
									} else {
										Utils.showAlertMessage(
												HomeScreenActivity.this, null,
												"PURCHASING NOT SUPPORTED , CHANGE MESSAGE");
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	public static void requestPurchase(SharedPreferences sp, String itemId) {
		try {
			JSONObject jo = new JSONObject();
			jo.put(KEY_TIME, System.currentTimeMillis());
			jo.put(KEY_ITEM_ID, itemId);
			sp.edit().putString(KEY_PURCHASE_COMMAND, jo.toString()).commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
